package main

import (
	"fmt"
	"ginadmin/conf"
	"ginadmin/db"
	"ginadmin/models"
	"ginadmin/routes"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func main() {
	if initSql() { //初始化数据库成功之后才进行下一步
		//createTable() //----生产时需要注释掉。会拖累启动速度
		//初始化web
		initWeb()
	}
}

func createTable() {
	//TODO 建库
	DB := db.GetInstance().GetDB()
	DB.AutoMigrate(&models.Organization{})
	DB.AutoMigrate(&models.User{})
	DB.AutoMigrate(&models.Menu{})
	DB.AutoMigrate(&models.Role{})

	fmt.Println("建库完毕")
}

func initSql() bool {
	initSqlResult := db.GetInstance().InitDB(conf.Cfg.DbUser, conf.Cfg.DbPwd, conf.Cfg.DbHost, conf.Cfg.DbName)
	if !initSqlResult {
		fmt.Println("初始化数据库失败")
	}
	return initSqlResult
}

func initWeb() {
	// 1.创建路由
	r := gin.New()
	r.Use(gin.Logger())
	routes.CommonHandler(r)
	//没有找到路由
	r.NoRoute(func(c *gin.Context) {
		c.String(http.StatusNotFound, "404 not found")
	})
	initHttpServer(r)
}

func initHttpServer(r *gin.Engine) {
	srv := &http.Server{
		Addr:           conf.Cfg.Listen,
		Handler:        r,
		ReadTimeout:    30 * time.Second,
		WriteTimeout:   60 * time.Second,
		MaxHeaderBytes: 1 << 20, // 1 MB
	}
	fmt.Println("初始化web完毕")
	srv.ListenAndServe()
}
